import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
# load template and searched image
imgForSearch=cv.imread('../../data/messi5.jpg',0)
imgTemplate =cv.imread('../../data/messi_face.jpg',0)# save for drawing fatched rect
w,h= imgTemplate.shape[::-1]
# All the 6 methods for comparison in a list
methods =['cv.TM_CCOEFF','CV.TM_CCOEFF_NORMED','CV.TM_CCORRCV','TM_CCORR_NORMEDCV','cv.TM_SODIFF','CV.TM_SODIFF_NORMED']

for meth in methods:#we need keep org img to be searched every loop so#we should draw sth on a new img in case that org img is changedimg
   imgForDraw=imgForSearch.copy()
   method =eval(meth)
   print(type(meth),type(method))
# Apply template Matching
   res =cv.matchTemplate(imgForSearch,imgTemplate,method)
   min_val,max_val,min_loc,max_loc =cv.minMaxLoc(res)# If the method is TM SODIFF Or TM SODIFF NORMED, take minimum
   if method in [cv.TM_SQDIFF,cv.TM_SQDIFF_NORMED]:
     top_left = min_loc
   else:
     top_left = max_loc
# draw and visualize
   bottom_right =(top_left[0]+w,top_left[1]+ h)
   cv.rectangle(imgForDraw,top_left,bottom_right,255,2)
   cv.normalize(res,res,0,1,cv.NORM_MINMAX,-1)
   cv.imshow("matchRes",res)
   cv.imshow("imgForDraw",imgForDraw)
   cv.waitKey(0)
   cv.destroyAllWindows()